package com.eight.group.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eight.group.constant.MessageConstant;
import com.eight.group.entity.PageResult;
import com.eight.group.entity.QueryPageBean;
import com.eight.group.entity.Result;
import com.eight.group.utils.DateUtils;
import com.xqx.eight.group.service.UserService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;

/**
 * @author：xingquanxiang createTime：2019/11/3 19:53
 * description:
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @RequestMapping("/getUsername")
    public Result getUsername() {
        // 当spring security完成用户认证后，会将信息保存到框架提供的上下文对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user != null) {
            System.out.println(user.getUsername());
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, user.getUsername());
        }
        return new Result(false, MessageConstant.GET_USERNAME_FAIL);
    }

    @RequestMapping("/findPage")
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public PageResult demo(@RequestBody QueryPageBean queryPageBean) {

        try {
            return userService.findPageByCondition(queryPageBean);
        } catch (Exception e) {
            e.printStackTrace();
            return new PageResult(0L, null);
        }
    }

    @RequestMapping("/add")
    @PreAuthorize("hasAuthority('USER_ADD')")
    public Result add(@RequestBody com.eight.group.pojo.User user, Integer[] roleIds) {

        try {
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
            userService.add(user, roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "新增用户失败");
        }
        return new Result(true, "新增用户成功");
    }

    @RequestMapping("/findById")
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public Result findById(Integer id) {
        try {
            com.eight.group.pojo.User user = userService.findById(id);
            return new Result(true, "查询用户信息成功", user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询用户信息失败");
        }
    }

    @RequestMapping("/delete")
    @PreAuthorize("hasAuthority('USER_DELETE')")
    public Result delete(Integer id) {
        try {
            userService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "删除失败");
        }
        return new Result(true, "删除成功");
    }

    @RequestMapping("/AlterRole")
    @PreAuthorize("hasAuthority('USER_EDIT')")
    public Result AlterRole(@RequestBody com.eight.group.pojo.User user, Integer[] roleIds) {

        try {
            userService.AlterRole(user, roleIds);
            return new Result(true, "修改角色成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "修改角色失败");
        }
    }


    @RequestMapping("/export.do")
    @PreAuthorize("hasAuthority('USER_QUERY')")
    public Result export(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        List<com.eight.group.pojo.User> list = userService.findAll();
        //获得Excel模板文件绝对路径
        String temlateRealPath = req.getSession().getServletContext().getRealPath("template") + File.separator + "user.xlsx";
//        System.out.println(temlateRealPath);
        //读取模板文件创建Excel表格对象
        XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(temlateRealPath)));

        XSSFSheet sheet = workbook.getSheetAt(0);//第一个分页
        for (int i = 0; i < list.size(); i++) {
            com.eight.group.pojo.User user = list.get(i);
            Date birthday = user.getBirthday();
            String gender = user.getGender();
            String username = user.getUsername();
            String remark = user.getRemark();
            String station = user.getStation();
            String telephone = user.getTelephone();


            XSSFRow row = sheet.createRow(i+1); //第i行
            if (birthday != null) {
                row.createCell(0).setCellValue(DateUtils.parseDate2String(birthday));
            }else{
                row.createCell(0).setCellValue("");
            }
            if (gender != null && gender.length() > 0) {
                row.createCell(1).setCellValue(gender);
            }else{
                row.createCell(1).setCellValue("");
            }
            if (username != null && username.length() > 0) {
                row.createCell(2).setCellValue(username);
            }else{
                row.createCell(2).setCellValue("");
            }
            if (remark != null && remark.length() > 0) {
                row.createCell(3).setCellValue(remark);
            }else{
                row.createCell(3).setCellValue("");
            }
            if (station != null && station.length() > 0) {
                row.createCell(4).setCellValue(station);
            }else{
                row.createCell(4).setCellValue("");
            }
            if (telephone != null && telephone.length() > 0) {
                row.createCell(5).setCellValue(telephone);
            }else{
                row.createCell(5).setCellValue("");
            }
        }

        //通过输出流进行文件下载
        ServletOutputStream out = resp.getOutputStream();
        resp.setContentType("application/vnd.ms-excel");    //代表Excel文件类型
        resp.setHeader("content-Disposition","attachment;filename=user.xlsx");
        workbook.write(out);
        out.flush();
        out.close();
        workbook.close();
        return null;
    }

}